package cn.guo.app.lan.msg.service;

import android.app.IntentService;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import cn.guo.app.lan.msg.interfaces.Callback;
import cn.guo.app.lan.msg.utils.G;

/**
 * 消息服务
 * Created by guo on 2015/10/29.
 */
public class MsgService extends IntentService {

    private static final String SERVICE_NAME = "MSG_SERVICE";

    //开启监听的端口,用于接收消息
    private static final int  LOCAL_PORT = 9999;
    //广播地址
    private static final String BROADCAST_HOST = "255.255.255.255";

    private Callback<String> callback;

    private MsgReceiveThread receiveThread;

    private MsgBinder binder = new MsgBinder();

    public MsgService() {
        super(SERVICE_NAME);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        G.w("启动了MSG服务");
        startReceiveThread();
    }

    @Override
    public IBinder onBind(Intent intent) {
        G.w("绑定了MSG服务");
        return binder;
    }

    @Override
    protected void onHandleIntent(Intent intent) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        G.w("关闭服务了");
        receiveThread.kill();
    }

    /**
     * 启动接收消息进程
     */
    private void startReceiveThread() {
        receiveThread = new MsgReceiveThread();
        receiveThread.start();
    }

    /***************************内部类*************************************/

    private class MsgReceiveThread extends Thread{
        private boolean flag = true;

        public void kill(){
            flag = false;
        }
        @Override
        public void run() {
            DatagramSocket ds = null;
            DatagramPacket dp;
            try {
                //绑定端口的
                ds = new DatagramSocket(LOCAL_PORT);
                G.w("监听广播端口打开：");
                while( flag) {
                    byte[] buf = new byte[1024];//存储发来的消息
                    dp = new DatagramPacket(buf, buf.length);
                    ds.receive(dp);
                    byte[] data = dp.getData();
                    if( data.length > 0 ) {
                        String msg = new String(data, 0, dp.getLength());
                        if (msg.length() > 0) {
                            G.w("收到广播消息：" + msg);
                            String ip = ds.getInetAddress().getHostAddress();
                            callback.run(ip,msg);
                        }
                    }
                    //G.w("收到广播消息：" + sb.toString());
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {

                if (ds != null) {
                    ds.close();
                }
            }
        }
    }


    public class MsgBinder extends Binder{

        public void setCallback(Callback<String> cb){
            callback = cb;
        }
        /**
         * 发送消息
         * @param message
         */
        public void sendMsg(String message){
            DatagramSocket sendSocket = null;
            try {
                sendSocket = new DatagramSocket();
                InetAddress adds = InetAddress.getByName(BROADCAST_HOST);
                DatagramPacket dp = new DatagramPacket(message.getBytes(),message.length(), adds, LOCAL_PORT);

                sendSocket.send(dp);
                sendSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(sendSocket != null){
                    sendSocket.close();
                }
            }
        }
    }
}
